<template>
  <view class="appointment-add-container">
    <view class="page-header">
      <text class="page-title">新增预约</text>
      <text class="page-subtitle">选择医生、日期和时间段进行预约</text>
    </view>

    <view class="form-container">
      <!-- 步骤1：选择患者 -->
      <view class="form-section">
        <text class="section-title">
          <text class="step-number">1</text> 患者信息
        </text>
        
        <view class="form-item">
          <text class="form-label required">患者</text>
          <picker 
            mode="selector" 
            :range="patientList" 
            range-key="label" 
            :value="selectedPatientIndex" 
            @change="onPatientChange"
          >
            <view class="picker-view">
              <text class="picker-text">{{ selectedPatientName || '请选择患者' }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
          <text v-if="errors.patient_id" class="error-text">{{ errors.patient_id }}</text>
        </view>
      </view>

      <!-- 步骤2：选择医生 -->
      <view class="form-section">
        <text class="section-title">
          <text class="step-number">2</text> 选择医生
        </text>
        
        <view class="form-item">
          <text class="form-label required">医生</text>
          <picker 
            mode="selector" 
            :range="doctorList" 
            range-key="label" 
            :value="selectedDoctorIndex" 
            @change="onDoctorChange"
          >
            <view class="picker-view">
              <text class="picker-text">{{ selectedDoctorName || '请选择医生' }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
          <text v-if="errors.doctor_id" class="error-text">{{ errors.doctor_id }}</text>
        </view>
      </view>

      <!-- 步骤3：选择日期 -->
      <view class="form-section" v-if="formData.doctor_id">
        <text class="section-title">
          <text class="step-number">3</text> 选择日期
        </text>
        
        <view class="form-item">
          <text class="form-label required">预约日期</text>
          <view v-if="availableDatesLoading" class="loading-text">加载中...</view>
          <picker 
            v-else-if="availableDates.length > 0"
            mode="selector" 
            :range="availableDates" 
            range-key="label" 
            :value="selectedDateIndex" 
            @change="onDateChange"
          >
            <view class="picker-view">
              <text class="picker-text">{{ selectedDateLabel || '请选择预约日期' }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
          <view v-else class="no-data-text">该医生暂无可用排班</view>
          <text v-if="errors.appointment_date" class="error-text">{{ errors.appointment_date }}</text>
        </view>
      </view>

      <!-- 步骤4：输入预计时长 -->
      <view class="form-section" v-if="formData.appointment_date">
        <text class="section-title">
          <text class="step-number">4</text> 预计时长
        </text>
        
        <view class="form-item">
          <text class="form-label required">预计时长（分钟）</text>
          <uni-easyinput 
            v-model="formData.duration_minutes"
            type="number"
            placeholder="请输入预计时长"
            :clearable="true"
            @blur="onDurationChange"
          />
          <text v-if="slotsNeeded > 0" class="info-text">
            需要占用 {{ slotsNeeded }} 个号源（每个{{ slotDuration }}分钟）
          </text>
          <text v-if="errors.duration_minutes" class="error-text">{{ errors.duration_minutes }}</text>
        </view>
      </view>

      <!-- 步骤5：选择时间段 -->
      <view class="form-section" v-if="formData.duration_minutes">
        <text class="section-title">
          <text class="step-number">5</text> 选择时间段
        </text>
        
        <view class="form-item">
          <text class="form-label required">起始时间</text>
          <view v-if="availableSlotsLoading" class="loading-text">加载号源中...</view>
          <view v-else-if="availableSlots.length > 0" class="time-slots-grid">
            <view 
              v-for="(slot, index) in availableSlots" 
              :key="index"
              class="time-slot-item"
              :class="{
                'slot-selected': formData.appointment_time === slot.time,
                'slot-disabled': !slot.available || !checkSlotAvailable(slot.time)
              }"
              @click="onTimeSlotClick(slot)"
            >
              <text class="slot-time">{{ slot.time }}</text>
              <text class="slot-status" v-if="!slot.available">已约</text>
              <text class="slot-status" v-else-if="!checkSlotAvailable(slot.time)">不足</text>
            </view>
          </view>
          <view v-else class="no-data-text">该日期暂无可用时间段</view>
          <text v-if="errors.appointment_time" class="error-text">{{ errors.appointment_time }}</text>
          <text v-if="consecutiveSlotsWarning" class="warning-text">{{ consecutiveSlotsWarning }}</text>
        </view>
      </view>

      <!-- 就诊信息 -->
      <view class="form-section" v-if="formData.appointment_time">
        <text class="section-title">就诊信息</text>
        
        <view class="form-item">
          <text class="form-label required">首复诊</text>
          <radio-group @change="onVisitTypeChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.visit_type === 1" color="#007aff"/>
              <text class="radio-text">初诊</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.visit_type === 2" color="#007aff"/>
              <text class="radio-text">复诊</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label required">主诉</text>
          <textarea 
            v-model="formData.chief_complaint" 
            class="form-textarea" 
            placeholder="请输入患者主诉"
            maxlength="500"
          />
          <text v-if="errors.chief_complaint" class="error-text">{{ errors.chief_complaint }}</text>
        </view>
      </view>

      <!-- 支付信息 -->
      <view class="form-section" v-if="formData.appointment_time">
        <text class="section-title">支付信息</text>
        
        <view class="form-item">
          <text class="form-label required">支付状态</text>
          <radio-group @change="onPaymentStatusChange" class="radio-group">
            <label class="radio-item">
              <radio value="0" :checked="formData.payment_status === 0" color="#007aff"/>
              <text class="radio-text">未支付</text>
            </label>
            <label class="radio-item">
              <radio value="1" :checked="formData.payment_status === 1" color="#007aff"/>
              <text class="radio-text">已支付</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.payment_status === 2" color="#007aff"/>
              <text class="radio-text">已退款</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label required">支付方式</text>
          <radio-group @change="onPaymentMethodChange" class="radio-group">
            <label class="radio-item">
              <radio value="0" :checked="formData.payment_method === 0" color="#007aff"/>
              <text class="radio-text">未选择</text>
            </label>
            <label class="radio-item">
              <radio value="1" :checked="formData.payment_method === 1" color="#007aff"/>
              <text class="radio-text">微信支付</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.payment_method === 2" color="#007aff"/>
              <text class="radio-text">支付宝</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.payment_method === 3" color="#007aff"/>
              <text class="radio-text">现金</text>
            </label>
          </radio-group>
        </view>
      </view>

      <!-- 预约摘要 -->
      <view class="form-section summary-section" v-if="formData.appointment_time">
        <text class="section-title">预约摘要</text>
        <view class="summary-item">
          <text class="summary-label">医生：</text>
          <text class="summary-value">{{ selectedDoctorName }}</text>
        </view>
        <view class="summary-item">
          <text class="summary-label">日期：</text>
          <text class="summary-value">{{ formData.appointment_date }}</text>
        </view>
        <view class="summary-item">
          <text class="summary-label">时间：</text>
          <text class="summary-value">{{ formData.appointment_time }}</text>
        </view>
        <view class="summary-item">
          <text class="summary-label">时长：</text>
          <text class="summary-value">{{ formData.duration_minutes }}分钟（{{ slotsNeeded }}个号源）</text>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-submit" @click="handleSubmit">提交预约</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const appointmentsObj = uniCloud.importObject('dh-appointments')
const dhSchedules = uniCloud.importObject('dh-doctor_schedules')

// 表单数据
const formData = reactive({
  patient_id: '',
  doctor_id: '',
  appointment_date: '',
  appointment_time: '',
  duration_minutes: '',
  visit_type: 1,
  chief_complaint: '',
  payment_status: 0,
  payment_method: 0,
  status: 1
})

// 错误信息
const errors = reactive({
  patient_id: '',
  doctor_id: '',
  appointment_date: '',
  appointment_time: '',
  duration_minutes: '',
  chief_complaint: ''
})

// 患者列表
const patientList = ref([])
const selectedPatientIndex = ref(-1)
const selectedPatientName = ref('')

// 医生列表
const doctorList = ref([])
const selectedDoctorIndex = ref(-1)
const selectedDoctorName = ref('')

// 可用日期列表
const availableDates = ref([])
const availableDatesLoading = ref(false)
const selectedDateIndex = ref(-1)
const selectedDateLabel = ref('')

// 可用时间段
const availableSlots = ref([])
const availableSlotsLoading = ref(false)
const slotDuration = ref(30)
const consecutiveSlotsWarning = ref('')

// 计算需要的号源数
const slotsNeeded = computed(() => {
  if (!formData.duration_minutes || !slotDuration.value) return 0
  return Math.ceil(parseInt(formData.duration_minutes) / slotDuration.value)
})

onMounted(() => {
  loadPatientList()
  loadDoctorList()
})

// 加载患者列表
async function loadPatientList() {
  try {
    const result = await appointmentsObj.getPatientList()
    if (result.success && result.data) {
      patientList.value = result.data
    }
  } catch (err) {
    console.error('加载患者列表失败:', err)
    uni.showToast({ title: '加载患者列表失败', icon: 'none' })
  }
}

// 加载医生列表
async function loadDoctorList() {
  try {
    const result = await dhSchedules.getDoctorList()
    if (result.success && result.data) {
      doctorList.value = result.data
    }
  } catch (err) {
    console.error('加载医生列表失败:', err)
    uni.showToast({ title: '加载医生列表失败', icon: 'none' })
  }
}

// 选择患者
function onPatientChange(e) {
  const index = e.detail.value
  selectedPatientIndex.value = index
  
  if (index >= 0 && index < patientList.value.length) {
    const patient = patientList.value[index]
    formData.patient_id = patient.value
    selectedPatientName.value = patient.label
    errors.patient_id = ''
  }
}

// 选择医生
async function onDoctorChange(e) {
  const index = e.detail.value
  selectedDoctorIndex.value = index
  
  if (index >= 0 && index < doctorList.value.length) {
    const doctor = doctorList.value[index]
    formData.doctor_id = doctor.value
    selectedDoctorName.value = doctor.label
    errors.doctor_id = ''
    
    // 清空后续选择
    resetDateSelection()
    
    // 加载该医生的可用日期
    await loadAvailableDates(doctor.value)
  }
}

// 加载可用日期
async function loadAvailableDates(doctorId) {
  availableDatesLoading.value = true
  availableDates.value = []
  
  try {
    const result = await appointmentsObj.getDoctorScheduleDates(doctorId)
    if (result.success && result.data) {
      availableDates.value = result.data.map(item => ({
        value: item.date,
        label: `${item.date}（可用${item.available_slots}/${item.total_slots}）`,
        available_slots: item.available_slots,
        total_slots: item.total_slots
      }))
    }
  } catch (err) {
    console.error('加载可用日期失败:', err)
    uni.showToast({ title: '加载可用日期失败', icon: 'none' })
  } finally {
    availableDatesLoading.value = false
  }
}

// 选择日期
async function onDateChange(e) {
  const index = e.detail.value
  selectedDateIndex.value = index
  
  if (index >= 0 && index < availableDates.value.length) {
    const date = availableDates.value[index]
    formData.appointment_date = date.value
    selectedDateLabel.value = date.label
    errors.appointment_date = ''
    
    // 清空后续选择
    resetTimeSelection()
    
    // 如果已经输入了时长，加载时间段
    if (formData.duration_minutes) {
      await loadAvailableSlots()
    }
  }
}

// 输入时长后加载时间段
async function onDurationChange() {
  if (!formData.duration_minutes || parseInt(formData.duration_minutes) <= 0) {
    errors.duration_minutes = '请输入有效的预计时长'
    return
  }
  
  errors.duration_minutes = ''
  
  // 如果已选择日期，加载时间段
  if (formData.appointment_date) {
    await loadAvailableSlots()
  }
}

// 加载可用时间段
async function loadAvailableSlots() {
  availableSlotsLoading.value = true
  availableSlots.value = []
  consecutiveSlotsWarning.value = ''
  
  try {
    const result = await appointmentsObj.getDoctorAvailableSlots(formData.doctor_id, formData.appointment_date)
    if (result.success && result.data) {
      slotDuration.value = result.data.slot_duration
      availableSlots.value = result.data.slots
    }
  } catch (err) {
    console.error('加载可用时间段失败:', err)
    uni.showToast({ title: '加载可用时间段失败', icon: 'none' })
  } finally {
    availableSlotsLoading.value = false
  }
}

// 检查从某时间开始是否有足够的连续号源
function checkSlotAvailable(startTime) {
  if (!startTime || slotsNeeded.value <= 0) return false
  
  const startIndex = availableSlots.value.findIndex(s => s.time === startTime)
  if (startIndex === -1) return false
  
  // 检查是否有足够的后续号源
  for (let i = 0; i < slotsNeeded.value; i++) {
    const slotIndex = startIndex + i
    if (slotIndex >= availableSlots.value.length || !availableSlots.value[slotIndex].available) {
      return false
    }
  }
  
  return true
}

// 选择时间段
function onTimeSlotClick(slot) {
  if (!slot.available) {
    uni.showToast({ title: '该时间段已被预约', icon: 'none' })
    return
  }
  
  if (!checkSlotAvailable(slot.time)) {
    consecutiveSlotsWarning.value = `从${slot.time}开始没有足够的连续号源，请选择其他时间或更换日期`
    uni.showToast({ title: '连续号源不足', icon: 'none' })
    return
  }
  
  formData.appointment_time = slot.time
  errors.appointment_time = ''
  consecutiveSlotsWarning.value = ''
}

// 重置日期选择
function resetDateSelection() {
  formData.appointment_date = ''
  selectedDateIndex.value = -1
  selectedDateLabel.value = ''
  availableDates.value = []
  resetTimeSelection()
}

// 重置时间选择
function resetTimeSelection() {
  formData.appointment_time = ''
  availableSlots.value = []
  consecutiveSlotsWarning.value = ''
}

function onVisitTypeChange(e) {
  formData.visit_type = parseInt(e.detail.value)
}

function onPaymentStatusChange(e) {
  formData.payment_status = parseInt(e.detail.value)
}

function onPaymentMethodChange(e) {
  formData.payment_method = parseInt(e.detail.value)
}

function validateForm() {
  let isValid = true
  
  if (!formData.patient_id) {
    errors.patient_id = '请选择患者'
    isValid = false
  }
  
  if (!formData.doctor_id) {
    errors.doctor_id = '请选择医生'
    isValid = false
  }
  
  if (!formData.appointment_date) {
    errors.appointment_date = '请选择预约日期'
    isValid = false
  }
  
  if (!formData.appointment_time) {
    errors.appointment_time = '请选择预约时间'
    isValid = false
  }
  
  if (!formData.duration_minutes || parseInt(formData.duration_minutes) <= 0) {
    errors.duration_minutes = '请输入有效的预计时长'
    isValid = false
  }
  
  if (!formData.chief_complaint || formData.chief_complaint.trim() === '') {
    errors.chief_complaint = '请输入患者主诉'
    isValid = false
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请完善表单信息', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '提交中...' })
    
    const submitData = {
      patient_id: formData.patient_id,
      doctor_id: formData.doctor_id,
      appointment_date: formData.appointment_date,
      appointment_time: formData.appointment_time,
      duration_minutes: parseInt(formData.duration_minutes),
      visit_type: formData.visit_type,
      chief_complaint: formData.chief_complaint,
      payment_status: formData.payment_status,
      payment_method: formData.payment_method,
      status: formData.status
    }
    
    const result = await appointmentsObj.bookAppointmentWithSlots(submitData)
    
    uni.hideLoading()
    
    if (result.success) {
      uni.showToast({ title: '预约创建成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/appointments/list' })
      }, 1500)
    } else {
      uni.showToast({ title: result.message || '创建失败', icon: 'none' })
    }
  } catch (err) {
    console.error('创建失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '创建失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/appointments/list' })
}
</script>

<style scoped>
.appointment-add-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 30rpx;
}

.page-header {
  background: #007aff;
  padding: 40rpx 30rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
}

.page-title {
  display: block;
  font-size: 40rpx;
  font-weight: bold;
  color: #ffffff;
  margin-bottom: 10rpx;
}

.page-subtitle {
  display: block;
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
}

.form-container {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 40rpx;
}

.form-section {
  margin-bottom: 50rpx;
}

.form-section:last-of-type {
  margin-bottom: 80rpx;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 30rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 30rpx;
  padding-bottom: 15rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.step-number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 44rpx;
  height: 44rpx;
  background: #007aff;
  color: #ffffff;
  border-radius: 50%;
  font-size: 24rpx;
  margin-right: 15rpx;
}

.form-item {
  margin-bottom: 35rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 15rpx;
}

.form-label.required::before {
  content: '* ';
  color: #ff4444;
}

.picker-view {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 25rpx;
  background-color: #ffffff;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
}

.picker-view:active {
  background-color: #f8f9fa;
}

.picker-text {
  font-size: 28rpx;
  color: #333333;
}

.picker-arrow {
  font-size: 28rpx;
  color: #999999;
}

.loading-text {
  padding: 30rpx;
  text-align: center;
  font-size: 28rpx;
  color: #999999;
}

.no-data-text {
  padding: 30rpx;
  text-align: center;
  font-size: 28rpx;
  color: #999999;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

.info-text {
  display: block;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #007aff;
}

.warning-text {
  display: block;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #ff9500;
}

.error-text {
  display: block;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #ff4444;
}

.time-slots-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}

.time-slot-item {
  position: relative;
  padding: 20rpx;
  text-align: center;
  background-color: #ffffff;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  cursor: pointer;
}

.time-slot-item.slot-selected {
  background: #007aff;
  border-color: #007aff;
}

.time-slot-item.slot-selected .slot-time {
  color: #ffffff;
}

.time-slot-item.slot-disabled {
  background-color: #f0f0f0;
  opacity: 0.5;
  pointer-events: none;
}

.slot-time {
  display: block;
  font-size: 28rpx;
  color: #333333;
}

.slot-status {
  display: block;
  margin-top: 5rpx;
  font-size: 20rpx;
  color: #ff4444;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 30rpx;
}

.radio-item {
  display: flex;
  align-items: center;
}

.radio-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333333;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  background-color: #ffffff;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333333;
  box-sizing: border-box;
}

.summary-section {
  background: #f8f9fa;
  padding: 30rpx;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.summary-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-label {
  font-size: 28rpx;
  color: #666666;
  min-width: 120rpx;
}

.summary-value {
  font-size: 28rpx;
  color: #333333;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  gap: 30rpx;
  margin-top: 50rpx;
}

.btn {
  flex: 1;
  padding: 25rpx;
  border-radius: 8rpx;
  font-size: 30rpx;
  text-align: center;
  border: none;
}

.btn-cancel {
  background-color: #f8f9fa;
  color: #666666;
  border: 2rpx solid #e0e0e0;
}

.btn-cancel:active {
  background-color: #e9ecef;
}

.btn-submit {
  background: #007aff;
  color: #ffffff;
}

.btn-submit:active {
  background: #0051d5;
}
</style>
